package org.dromara.authcode.service.impl;

import cn.hutool.core.convert.Convert;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.authcode.domain.bo.TDeviceBo;
import org.dromara.authcode.domain.vo.TDeviceVo;
import org.dromara.authcode.domain.TDevice;
import org.dromara.authcode.mapper.TDeviceMapper;
import org.dromara.authcode.service.ITDeviceService;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 *
 * @author Miles Meng
 * @date 2025-08-08
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TDeviceServiceImpl implements ITDeviceService {
    private final TDeviceMapper baseMapper;


    /**
     * 查询设备信息
     *
     * @param id 主键
     * @return 设备信息
     */
    @Override
    public TDeviceVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 根据MAC地址查询设备信息
     * 数据库中设置唯一索引
     * @param macAddress MAC地址
     * @return 设备信息
     */
    @Override
    public TDevice queryByMacAddress(String macAddress){
        LambdaQueryWrapper<TDevice> lqw = Wrappers.lambdaQuery();
        lqw.eq(TDevice::getMacAddress, macAddress);
        lqw.last("limit 1");
        return baseMapper.selectOne(lqw);
    }

    /**
     * 分页查询设备信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 设备信息分页列表
     */
    @Override
    public TableDataInfo<TDeviceVo> queryPageList(TDeviceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TDevice> lqw = buildQueryWrapper(bo);
        Page<TDeviceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的设备信息列表
     *
     * @param bo 查询条件
     * @return 设备信息列表
     */
    @Override
    public List<TDeviceVo> queryList(TDeviceBo bo) {
        LambdaQueryWrapper<TDevice> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TDevice> buildQueryWrapper(TDeviceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TDevice> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TDevice::getId);
        lqw.eq(bo.getUserId() != null, TDevice::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getMacAddress()), TDevice::getMacAddress, bo.getMacAddress());
        lqw.eq(bo.getValidTime() != null, TDevice::getValidTime, bo.getValidTime());
        lqw.eq(bo.getActiveStatus() != null, TDevice::getActiveStatus, bo.getActiveStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getBoard()), TDevice::getBoard, bo.getBoard());
        lqw.eq(StringUtils.isNotBlank(bo.getAlias()), TDevice::getAlias, bo.getAlias());
        lqw.eq(StringUtils.isNotBlank(bo.getAppVersion()), TDevice::getAppVersion, bo.getAppVersion());
        return lqw;
    }

    /**
     * 新增设备信息
     *
     * @param bo 设备信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TDeviceBo bo) {
        TDevice add = MapstructUtils.convert(bo, TDevice.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改设备信息
     *
     * @param bo 设备信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TDeviceBo bo) {
        TDevice update = MapstructUtils.convert(bo, TDevice.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TDevice entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除设备信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 导入设备信息
     * @param file 设备信息Excel文件
     * @return 是否导入成功
     */
    @Override
    public boolean importDevices(MultipartFile file) throws IOException {
        // 读取Excel文件
        ExcelResult<TDeviceVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), TDeviceVo.class, true);
        List<TDeviceVo> list = MapstructUtils.convert(excelResult.getList(), TDeviceVo.class);

        if (list == null || list.isEmpty()) {
            return false;
        }

        List<TDevice> entities = list.stream().map(vo -> Convert.convert(TDevice.class, vo)).collect(Collectors.toList());
        return baseMapper.insertOrUpdateBatch(entities);

    }
}
